package com.example.txtransaction;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(sqlSessionFactoryRef = "sqlSessionFactoryB",basePackages = "com.example.txtransaction.b")
public class DataSourceConfigB {

    @Bean(value = "dataSourceB")
    @ConfigurationProperties(prefix = "spring.b.datasource")
    public DataSource dataSourceB(){
        return DataSourceBuilder.create().build();
    }

    @Bean(value = "mysqlXADataSourceB")
    @ConfigurationProperties(prefix = "spring.b.datasource")
    public MysqlXADataSource mysqlXADataSourceB(){
        return new MysqlXADataSource();
    }

    @DependsOn(value = "mysqlXADataSourceB")
    @Bean(value = "dataSourceXB")
    public DataSource dataSourceXB(MysqlXADataSource mysqlXADataSourceB){
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setXaDataSource(mysqlXADataSourceB);
        atomikosDataSourceBean.setUniqueResourceName("dataSourceXB");
        return atomikosDataSourceBean;
    }

    @Bean(value = "sqlSessionFactoryB")
    public SqlSessionFactory sqlSessionFactoryB(@Qualifier(value = "dataSourceXB")DataSource dataSourceB) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSourceB);
        factory.setTypeAliasesPackage("com.example.txtransaction.entity");
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        Resource[] mappers = resourceResolver.getResources("classpath*:/mapper/b/*.xml");
        factory.setMapperLocations(mappers);
//        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//        configuration.setMapUnderscoreToCamelCase(true);
//        factory.setConfiguration(configuration);
        return factory.getObject();
    }

}
